package cn.base.web.support.id;


import cn.rengy.isql.Dao;
import cn.rengy.isql.DbService;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
/**
 * 数据库标sys_worker_node维护worker，数据库需要中心化
 * hostname唯一
 * hostname+node_id(重启一次+1) 确定一个服务
 * 服务停止时当node_id一致时减1
 * 微服务中使用多数据源
 * @author rengy
 *
 */
@Service
@DS("admin")
public class SysWorkerNodeService {
	@Autowired(required = false)
	private DbService dbService;
	@Autowired(required = false)
	private Dao dao;

	@Transactional(rollbackFor = Exception.class)
	public SysWorkerNodePO getWorker(String hostname, String ip) {
		
		SysWorkerNodePO worderNode= dbService.queryForBean("select_unique_worker", SysWorkerNodePO.class, hostname);
		Date now=new Date();
		if(worderNode==null){
			worderNode= new SysWorkerNodePO();
			worderNode.setCreateTime(now);
			worderNode.setHostname(hostname);
			worderNode.setIp(ip);
			//worderNode.setPort(port);
			worderNode.setRestartNumber(0);
			worderNode.setLastModified(now);
			//worderNode.setType(type);
			//新增 只有mysql有自增主键，所以这里需要改下，适配其他数据库
			//TODO 适配其他数据库后需要考虑并发情况
			Integer maxId=dao.querySingleColumn("select max(worker_id) m from sys_worker_node",Integer.class);
			if(maxId==null){
				worderNode.setWorkerId(1);
			}else{
				worderNode.setWorkerId(maxId.intValue()+1);
			}
			dbService.updateBeanParameter("insert_sys_worker_node", worderNode);
		}
		//更新Restart_number
		this.dbService.update("update_sys_worker_node_restart_number", worderNode.getWorkerId());
		
		return worderNode;
	}
	
	public void stop(int workerId,int startNumber) {
		dao.update("update sys_worker_node set restart_number=restart_number-1 where worker_id=? and restart_number=?", workerId,startNumber+1);
	}
}
